package org.jeecg.modules.vital.controller;

import org.jeecg.common.system.query.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import java.util.Arrays;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.vital.entity.Allergichistory;
import org.jeecg.modules.vital.entity.Present;
import org.jeecg.modules.vital.entity.History;
import org.jeecg.modules.vital.entity.Diagnosis;
import org.jeecg.modules.vital.entity.TreatmentPlanning;
import org.jeecg.modules.vital.entity.MedicalRecordInformation;
import org.jeecg.modules.vital.service.IMedicalRecordInformationService;
import org.jeecg.modules.vital.service.IAllergichistoryService;
import org.jeecg.modules.vital.service.IPresentService;
import org.jeecg.modules.vital.service.IHistoryService;
import org.jeecg.modules.vital.service.IDiagnosisService;
import org.jeecg.modules.vital.service.ITreatmentPlanningService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 病历信息
 * @Author: jeecg-boot
 * @Date:   2023-01-04
 * @Version: V1.0
 */
@Api(tags="病历信息")
@RestController
@RequestMapping("/vital/medicalRecordInformation")
@Slf4j
public class MedicalRecordInformationController extends JeecgController<MedicalRecordInformation, IMedicalRecordInformationService> {

	@Autowired
	private IMedicalRecordInformationService medicalRecordInformationService;

	@Autowired
	private IAllergichistoryService allergichistoryService;

	@Autowired
	private IPresentService presentService;

	@Autowired
	private IHistoryService historyService;

	@Autowired
	private IDiagnosisService diagnosisService;

	@Autowired
	private ITreatmentPlanningService treatmentPlanningService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param medicalRecordInformation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "病历信息-分页列表查询")
	@ApiOperation(value="病历信息-分页列表查询", notes="病历信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<MedicalRecordInformation>> queryPageList(MedicalRecordInformation medicalRecordInformation,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MedicalRecordInformation> queryWrapper = QueryGenerator.initQueryWrapper(medicalRecordInformation, req.getParameterMap());
		Page<MedicalRecordInformation> page = new Page<MedicalRecordInformation>(pageNo, pageSize);
		IPage<MedicalRecordInformation> pageList = medicalRecordInformationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
     *   添加
     * @param medicalRecordInformation
     * @return
     */
    @AutoLog(value = "病历信息-添加")
    @ApiOperation(value="病历信息-添加", notes="病历信息-添加")
    @RequiresPermissions("vital:medical_record_information:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MedicalRecordInformation medicalRecordInformation) {
        medicalRecordInformationService.save(medicalRecordInformation);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param medicalRecordInformation
     * @return
     */
    @AutoLog(value = "病历信息-编辑")
    @ApiOperation(value="病历信息-编辑", notes="病历信息-编辑")
    @RequiresPermissions("vital:medical_record_information:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
    public Result<String> edit(@RequestBody MedicalRecordInformation medicalRecordInformation) {
        medicalRecordInformationService.updateById(medicalRecordInformation);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "病历信息-通过id删除")
    @ApiOperation(value="病历信息-通过id删除", notes="病历信息-通过id删除")
    @RequiresPermissions("vital:medical_record_information:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        medicalRecordInformationService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "病历信息-批量删除")
    @ApiOperation(value="病历信息-批量删除", notes="病历信息-批量删除")
    @RequiresPermissions("vital:medical_record_information:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.medicalRecordInformationService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequiresPermissions("vital:medical_record_information:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MedicalRecordInformation medicalRecordInformation) {
        return super.exportXls(request, medicalRecordInformation, MedicalRecordInformation.class, "病历信息");
    }

    /**
     * 导入
     * @return
     */
    @RequiresPermissions("vital:medical_record_information:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MedicalRecordInformation.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-过敏史章节-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "过敏史章节-通过主表ID查询")
	@ApiOperation(value="过敏史章节-通过主表ID查询", notes="过敏史章节-通过主表ID查询")
	@GetMapping(value = "/listAllergichistoryByMainId")
    public Result<IPage<Allergichistory>> listAllergichistoryByMainId(Allergichistory allergichistory,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<Allergichistory> queryWrapper = QueryGenerator.initQueryWrapper(allergichistory, req.getParameterMap());
        Page<Allergichistory> page = new Page<Allergichistory>(pageNo, pageSize);
        IPage<Allergichistory> pageList = allergichistoryService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param allergichistory
	 * @return
	 */
	@AutoLog(value = "过敏史章节-添加")
	@ApiOperation(value="过敏史章节-添加", notes="过敏史章节-添加")
	@PostMapping(value = "/addAllergichistory")
	public Result<String> addAllergichistory(@RequestBody Allergichistory allergichistory) {
		allergichistoryService.save(allergichistory);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param allergichistory
	 * @return
	 */
	@AutoLog(value = "过敏史章节-编辑")
	@ApiOperation(value="过敏史章节-编辑", notes="过敏史章节-编辑")
	@RequestMapping(value = "/editAllergichistory", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editAllergichistory(@RequestBody Allergichistory allergichistory) {
		allergichistoryService.updateById(allergichistory);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "过敏史章节-通过id删除")
	@ApiOperation(value="过敏史章节-通过id删除", notes="过敏史章节-通过id删除")
	@DeleteMapping(value = "/deleteAllergichistory")
	public Result<String> deleteAllergichistory(@RequestParam(name="id",required=true) String id) {
		allergichistoryService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "过敏史章节-批量删除")
	@ApiOperation(value="过敏史章节-批量删除", notes="过敏史章节-批量删除")
	@DeleteMapping(value = "/deleteBatchAllergichistory")
	public Result<String> deleteBatchAllergichistory(@RequestParam(name="ids",required=true) String ids) {
	    this.allergichistoryService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportAllergichistory")
    public ModelAndView exportAllergichistory(HttpServletRequest request, Allergichistory allergichistory) {
		 // Step.1 组装查询条件
		 QueryWrapper<Allergichistory> queryWrapper = QueryGenerator.initQueryWrapper(allergichistory, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<Allergichistory> pageList = allergichistoryService.list(queryWrapper);
		 List<Allergichistory> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "过敏史章节");
		 mv.addObject(NormalExcelConstants.CLASS, Allergichistory.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("过敏史章节报表", "导出人:" + sysUser.getRealname(), "过敏史章节"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importAllergichistory/{mainId}")
    public Result<?> importAllergichistory(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<Allergichistory> list = ExcelImportUtil.importExcel(file.getInputStream(), Allergichistory.class, params);
				 for (Allergichistory temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 allergichistoryService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-过敏史章节-end----------------------------------------------*/

    /*--------------------------------子表处理-现病史章节-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "现病史章节-通过主表ID查询")
	@ApiOperation(value="现病史章节-通过主表ID查询", notes="现病史章节-通过主表ID查询")
	@GetMapping(value = "/listPresentByMainId")
    public Result<IPage<Present>> listPresentByMainId(Present present,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<Present> queryWrapper = QueryGenerator.initQueryWrapper(present, req.getParameterMap());
        Page<Present> page = new Page<Present>(pageNo, pageSize);
        IPage<Present> pageList = presentService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param present
	 * @return
	 */
	@AutoLog(value = "现病史章节-添加")
	@ApiOperation(value="现病史章节-添加", notes="现病史章节-添加")
	@PostMapping(value = "/addPresent")
	public Result<String> addPresent(@RequestBody Present present) {
		presentService.save(present);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param present
	 * @return
	 */
	@AutoLog(value = "现病史章节-编辑")
	@ApiOperation(value="现病史章节-编辑", notes="现病史章节-编辑")
	@RequestMapping(value = "/editPresent", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editPresent(@RequestBody Present present) {
		presentService.updateById(present);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "现病史章节-通过id删除")
	@ApiOperation(value="现病史章节-通过id删除", notes="现病史章节-通过id删除")
	@DeleteMapping(value = "/deletePresent")
	public Result<String> deletePresent(@RequestParam(name="id",required=true) String id) {
		presentService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "现病史章节-批量删除")
	@ApiOperation(value="现病史章节-批量删除", notes="现病史章节-批量删除")
	@DeleteMapping(value = "/deleteBatchPresent")
	public Result<String> deleteBatchPresent(@RequestParam(name="ids",required=true) String ids) {
	    this.presentService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportPresent")
    public ModelAndView exportPresent(HttpServletRequest request, Present present) {
		 // Step.1 组装查询条件
		 QueryWrapper<Present> queryWrapper = QueryGenerator.initQueryWrapper(present, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<Present> pageList = presentService.list(queryWrapper);
		 List<Present> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "现病史章节");
		 mv.addObject(NormalExcelConstants.CLASS, Present.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("现病史章节报表", "导出人:" + sysUser.getRealname(), "现病史章节"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importPresent/{mainId}")
    public Result<?> importPresent(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<Present> list = ExcelImportUtil.importExcel(file.getInputStream(), Present.class, params);
				 for (Present temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 presentService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-现病史章节-end----------------------------------------------*/

    /*--------------------------------子表处理-既往史章节-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "既往史章节-通过主表ID查询")
	@ApiOperation(value="既往史章节-通过主表ID查询", notes="既往史章节-通过主表ID查询")
	@GetMapping(value = "/listHistoryByMainId")
    public Result<IPage<History>> listHistoryByMainId(History history,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<History> queryWrapper = QueryGenerator.initQueryWrapper(history, req.getParameterMap());
        Page<History> page = new Page<History>(pageNo, pageSize);
        IPage<History> pageList = historyService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param history
	 * @return
	 */
	@AutoLog(value = "既往史章节-添加")
	@ApiOperation(value="既往史章节-添加", notes="既往史章节-添加")
	@PostMapping(value = "/addHistory")
	public Result<String> addHistory(@RequestBody History history) {
		historyService.save(history);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param history
	 * @return
	 */
	@AutoLog(value = "既往史章节-编辑")
	@ApiOperation(value="既往史章节-编辑", notes="既往史章节-编辑")
	@RequestMapping(value = "/editHistory", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editHistory(@RequestBody History history) {
		historyService.updateById(history);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "既往史章节-通过id删除")
	@ApiOperation(value="既往史章节-通过id删除", notes="既往史章节-通过id删除")
	@DeleteMapping(value = "/deleteHistory")
	public Result<String> deleteHistory(@RequestParam(name="id",required=true) String id) {
		historyService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "既往史章节-批量删除")
	@ApiOperation(value="既往史章节-批量删除", notes="既往史章节-批量删除")
	@DeleteMapping(value = "/deleteBatchHistory")
	public Result<String> deleteBatchHistory(@RequestParam(name="ids",required=true) String ids) {
	    this.historyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportHistory")
    public ModelAndView exportHistory(HttpServletRequest request, History history) {
		 // Step.1 组装查询条件
		 QueryWrapper<History> queryWrapper = QueryGenerator.initQueryWrapper(history, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<History> pageList = historyService.list(queryWrapper);
		 List<History> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "既往史章节");
		 mv.addObject(NormalExcelConstants.CLASS, History.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("既往史章节报表", "导出人:" + sysUser.getRealname(), "既往史章节"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importHistory/{mainId}")
    public Result<?> importHistory(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<History> list = ExcelImportUtil.importExcel(file.getInputStream(), History.class, params);
				 for (History temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 historyService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-既往史章节-end----------------------------------------------*/

    /*--------------------------------子表处理-诊断记录-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "诊断记录-通过主表ID查询")
	@ApiOperation(value="诊断记录-通过主表ID查询", notes="诊断记录-通过主表ID查询")
	@GetMapping(value = "/listDiagnosisByMainId")
    public Result<IPage<Diagnosis>> listDiagnosisByMainId(Diagnosis diagnosis,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<Diagnosis> queryWrapper = QueryGenerator.initQueryWrapper(diagnosis, req.getParameterMap());
        Page<Diagnosis> page = new Page<Diagnosis>(pageNo, pageSize);
        IPage<Diagnosis> pageList = diagnosisService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param diagnosis
	 * @return
	 */
	@AutoLog(value = "诊断记录-添加")
	@ApiOperation(value="诊断记录-添加", notes="诊断记录-添加")
	@PostMapping(value = "/addDiagnosis")
	public Result<String> addDiagnosis(@RequestBody Diagnosis diagnosis) {
		diagnosisService.save(diagnosis);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param diagnosis
	 * @return
	 */
	@AutoLog(value = "诊断记录-编辑")
	@ApiOperation(value="诊断记录-编辑", notes="诊断记录-编辑")
	@RequestMapping(value = "/editDiagnosis", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editDiagnosis(@RequestBody Diagnosis diagnosis) {
		diagnosisService.updateById(diagnosis);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "诊断记录-通过id删除")
	@ApiOperation(value="诊断记录-通过id删除", notes="诊断记录-通过id删除")
	@DeleteMapping(value = "/deleteDiagnosis")
	public Result<String> deleteDiagnosis(@RequestParam(name="id",required=true) String id) {
		diagnosisService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "诊断记录-批量删除")
	@ApiOperation(value="诊断记录-批量删除", notes="诊断记录-批量删除")
	@DeleteMapping(value = "/deleteBatchDiagnosis")
	public Result<String> deleteBatchDiagnosis(@RequestParam(name="ids",required=true) String ids) {
	    this.diagnosisService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportDiagnosis")
    public ModelAndView exportDiagnosis(HttpServletRequest request, Diagnosis diagnosis) {
		 // Step.1 组装查询条件
		 QueryWrapper<Diagnosis> queryWrapper = QueryGenerator.initQueryWrapper(diagnosis, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<Diagnosis> pageList = diagnosisService.list(queryWrapper);
		 List<Diagnosis> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "诊断记录");
		 mv.addObject(NormalExcelConstants.CLASS, Diagnosis.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("诊断记录报表", "导出人:" + sysUser.getRealname(), "诊断记录"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importDiagnosis/{mainId}")
    public Result<?> importDiagnosis(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<Diagnosis> list = ExcelImportUtil.importExcel(file.getInputStream(), Diagnosis.class, params);
				 for (Diagnosis temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 diagnosisService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-诊断记录-end----------------------------------------------*/

    /*--------------------------------子表处理-治疗计划-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	//@AutoLog(value = "治疗计划-通过主表ID查询")
	@ApiOperation(value="治疗计划-通过主表ID查询", notes="治疗计划-通过主表ID查询")
	@GetMapping(value = "/listTreatmentPlanningByMainId")
    public Result<IPage<TreatmentPlanning>> listTreatmentPlanningByMainId(TreatmentPlanning treatmentPlanning,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<TreatmentPlanning> queryWrapper = QueryGenerator.initQueryWrapper(treatmentPlanning, req.getParameterMap());
        Page<TreatmentPlanning> page = new Page<TreatmentPlanning>(pageNo, pageSize);
        IPage<TreatmentPlanning> pageList = treatmentPlanningService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

	/**
	 * 添加
	 * @param treatmentPlanning
	 * @return
	 */
	@AutoLog(value = "治疗计划-添加")
	@ApiOperation(value="治疗计划-添加", notes="治疗计划-添加")
	@PostMapping(value = "/addTreatmentPlanning")
	public Result<String> addTreatmentPlanning(@RequestBody TreatmentPlanning treatmentPlanning) {
		treatmentPlanningService.save(treatmentPlanning);
		return Result.OK("添加成功！");
	}

    /**
	 * 编辑
	 * @param treatmentPlanning
	 * @return
	 */
	@AutoLog(value = "治疗计划-编辑")
	@ApiOperation(value="治疗计划-编辑", notes="治疗计划-编辑")
	@RequestMapping(value = "/editTreatmentPlanning", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editTreatmentPlanning(@RequestBody TreatmentPlanning treatmentPlanning) {
		treatmentPlanningService.updateById(treatmentPlanning);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "治疗计划-通过id删除")
	@ApiOperation(value="治疗计划-通过id删除", notes="治疗计划-通过id删除")
	@DeleteMapping(value = "/deleteTreatmentPlanning")
	public Result<String> deleteTreatmentPlanning(@RequestParam(name="id",required=true) String id) {
		treatmentPlanningService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "治疗计划-批量删除")
	@ApiOperation(value="治疗计划-批量删除", notes="治疗计划-批量删除")
	@DeleteMapping(value = "/deleteBatchTreatmentPlanning")
	public Result<String> deleteBatchTreatmentPlanning(@RequestParam(name="ids",required=true) String ids) {
	    this.treatmentPlanningService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportTreatmentPlanning")
    public ModelAndView exportTreatmentPlanning(HttpServletRequest request, TreatmentPlanning treatmentPlanning) {
		 // Step.1 组装查询条件
		 QueryWrapper<TreatmentPlanning> queryWrapper = QueryGenerator.initQueryWrapper(treatmentPlanning, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<TreatmentPlanning> pageList = treatmentPlanningService.list(queryWrapper);
		 List<TreatmentPlanning> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "治疗计划");
		 mv.addObject(NormalExcelConstants.CLASS, TreatmentPlanning.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("治疗计划报表", "导出人:" + sysUser.getRealname(), "治疗计划"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importTreatmentPlanning/{mainId}")
    public Result<?> importTreatmentPlanning(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
       // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<TreatmentPlanning> list = ExcelImportUtil.importExcel(file.getInputStream(), TreatmentPlanning.class, params);
				 for (TreatmentPlanning temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 treatmentPlanningService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-治疗计划-end----------------------------------------------*/




}
